export default class AIController {
  constructor(cueBall, objectBalls, game) {
    this.cueBall = cueBall;
    this.objectBalls = objectBalls;
    this.game = game;
  }

  takeShot() {
    // 模拟思考时间
    setTimeout(() => {
      if (!this.cueBall || this.cueBall.isPocketed) return;
      const choice = this.chooseTargetBall();
      const target = choice && choice.ball;
      const pocket = choice && choice.pocket;
      if (!target) return;

      const dx = target.x - this.cueBall.x;
      const dy = target.y - this.cueBall.y;
      const len = Math.sqrt(dx * dx + dy * dy) || 1;
      const toBall = { x: dx / len, y: dy / len };

      // 略微朝袋口方向修正（使目标球更朝 pocket 前进）
      let aim = toBall;
      if (pocket) {
        const bx = pocket.x - target.x;
        const by = pocket.y - target.y;
        const bl = Math.sqrt(bx * bx + by * by) || 1;
        const toPocket = { x: bx / bl, y: by / bl };
        const alpha = 0.15; // 修正权重
        aim = { x: toBall.x * (1 - alpha) + toPocket.x * alpha, y: toBall.y * (1 - alpha) + toPocket.y * alpha };
        const aimLen = Math.sqrt(aim.x * aim.x + aim.y * aim.y) || 1;
        aim = { x: aim.x / aimLen, y: aim.y / aimLen };
      }

      const distance = Math.sqrt(dx * dx + dy * dy);
      const power = Math.max(300, Math.min(distance * 3.2, 1200));

      this.cueBall.vx = aim.x * power;
      this.cueBall.vy = aim.y * power;

      this.game.notifyShotStarted();
    }, 700);
  }

  chooseTargetBall() {
    // 选择与最近袋口更对齐的目标球（角度更小）
    let best = null;
    let bestScore = Number.MAX_VALUE;

    const table = this.game && this.game.table;
    for (const b of this.objectBalls) {
      if (!b || b.isPocketed) continue;

      const cx = b.x - this.cueBall.x;
      const cy = b.y - this.cueBall.y;
      const cl = Math.sqrt(cx * cx + cy * cy) || 1;
      const vCB = { x: cx / cl, y: cy / cl };

      // 找到该球最近的袋口
      let nearestPocket = null;
      let nearestDist = Number.MAX_VALUE;
      if (table && table.pockets) {
        for (const p of table.pockets) {
          const dx = p.x - b.x;
          const dy = p.y - b.y;
          const d = Math.sqrt(dx * dx + dy * dy);
          if (d < nearestDist) {
            nearestDist = d;
            nearestPocket = p;
          }
        }
      }

      // 与袋口方向的对齐角度
      let angle = Math.PI;
      if (nearestPocket) {
        const px = nearestPocket.x - b.x;
        const py = nearestPocket.y - b.y;
        const pl = Math.sqrt(px * px + py * py) || 1;
        const vBP = { x: px / pl, y: py / pl };
        const dot = vCB.x * vBP.x + vCB.y * vBP.y;
        angle = Math.acos(Math.max(-1, Math.min(1, dot)));
      }

      // 综合评分：角度 + 少量距离惩罚
      const score = angle + nearestDist * 0.0008;

      if (score < bestScore) {
        bestScore = score;
        best = { ball: b, pocket: nearestPocket };
      }
    }
    return best;
  }
}